package com.example.wisdomclassroomapi.facade.controller.common;

import com.example.wisdomclassroomapi.common.dto.ResponseDto;
import com.example.wisdomclassroomapi.common.exception.ApplicationException;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice()
public class MyResponseBodyAdvice implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return !returnType.getParameterType().equals(ResponseDto.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        return ResponseDto.success(body);
    }

    @ExceptionHandler(value = { ApplicationException.class })
    @ResponseBody
    public Object exception(ApplicationException e) {
        return ResponseDto.fail(e.getCode(),e.getMessage());
    }
}
